package com.example.bootredis.utils;


import java.util.concurrent.locks.ReentrantReadWriteLock;

public class SynchronizedDemo3 {
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    public static void main(String[] args) throws Exception {
        final SynchronizedDemo3 test = new SynchronizedDemo3();
        for (int i = 0; i < 10; i++) {
            if (i == 3){
                new Thread(() -> {
                    try {
                        test.write(Thread.currentThread());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            }else {
                new Thread(() -> {
                    try {
                        test.get(Thread.currentThread());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        }
  /*
        new Thread(() -> {
            try {
                test.get(Thread.currentThread());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();*/


    }

    public void get(Thread thread) throws Exception {
        long start = System.currentTimeMillis();
        rwl.readLock().lock();
        try {
            System.out.println(thread.getName() + "读操作睡觉");
            Thread.sleep(100);
            System.out.println(thread.getName() + "读的时候醒了");
        } finally {
            rwl.readLock().unlock();
        }

    }


    public void write(Thread thread) throws Exception {
        long start = System.currentTimeMillis();
        rwl.writeLock().lock();
        try {
            System.out.println(thread.getName() + "写-------------操作睡觉");
            Thread.sleep(1000);
            System.out.println(thread.getName() + "写-------------的时候醒了");
        } finally {
            rwl.writeLock().unlock();
        }

    }
}
